<template>
  <view class="goods-container">
    <view class="header">
      <nut-input class="left" v-model="keywords" clearable :border="false" placeholder="请输入您的货物包装"
        @update:model-value="changeInput">
      </nut-input>
      <view class="cancel" v-if="!keywords.trim()" @click="goback">取消</view>
      <view class="cancel" v-else @click="chooseGoodsName(keywords)">确定</view>
      <view class="select-list" v-if="selectList.length">
        <view class="select-item" v-for="(item, index) in selectList" :key="index" v-html="item.str"
          @click="chooseGoodsName(item.ssopRemark)"></view>
      </view>
    </view>
    <nut-tabs v-model="tabValue" title-gutter="48rpx" class="tabs" v-if="!keywords">
      <nut-tab-pane title="最近常寄" pane-key="1">
        <view class="historys">
          <view class="history-item" v-for="(item, index) in historyKeywords" :key="index"
            @click="chooseGoodsName(item.name)">
            {{ item.name }}</view>
        </view>
      </nut-tab-pane>
      <nut-tab-pane title="常用货物包装" pane-key="2">
        <view class="elevators">
          <nut-elevator :index-list="elevatorList" @click-item.native="clickItem" @click-index="clickIndex"
            height="calc(100vh - 240rpx)"></nut-elevator>
        </view>
      </nut-tab-pane>
    </nut-tabs>
  </view>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import Taro, { useDidShow } from "@tarojs/taro";
import { getNameGoods } from "@/@api/wait"; // 待确认页面接口

import { pinyin } from "pinyin-pro";
const keywords = ref<string>('')
const tabValue = ref<string>('1')
const historyKeywords = ref<string[]>([])
const list = ref<any>([])
const elevatorList = ref<object[]>([])
const selectList = ref<object[]>([])


useDidShow(() => {
  initList(); // 初始化货物包装
  historyKeywords.value = getRecentlyShippedGoods(); // 取出最近常寄赋值
});

// 前端查询
const changeInput = () => {
  if (!keywords.value) {
    selectList.value = []
    return
  }
  selectList.value = list.value.filter((item) => {
    return item.ssopRemark.indexOf(keywords.value) !== -1
  }).map((item) => {
    return {
      ...item,
      str: item.ssopRemark.replace(keywords.value, `<text style="color:#0966ff">${keywords.value}</text>`)
    }
  })
  // 更新常寄货物数组
  updateRecentlyShippedGoods(keywords.value);
}

// 选择常寄货物包装
const chooseGoodsName = (item) => {
  let pages = Taro.getCurrentPages()
  let prevPage = pages[pages.length - 2]
  prevPage.setData({goodsPack: item})
  Taro.navigateBack()
}

// 点击选中货物包装
const clickItem = (key:number,item: any) => {
  // 存入本地常寄 
  updateRecentlyShippedGoods(item.ssopRemark);
  let pages = Taro.getCurrentPages()
  let prevPage = pages[pages.length - 2]
  prevPage.setData({goodsPack: item.ssopRemark})
  Taro.navigateBack()
}

// 存入最近常寄货物包装
function saveRecentlyShippedGoods(recentGoods) {
  Taro.setStorageSync('recentlyShippedGoodsPack', JSON.stringify(recentGoods));
}

// 取出最近常寄货物包装数组
function getRecentlyShippedGoods() {
  const data = Taro.getStorageSync('recentlyShippedGoodsPack');
  return data ? JSON.parse(data) : [];
}

// 更新最近常寄货物数组
function updateRecentlyShippedGoods(query) {
  const recentlyShippedGoodsPack = getRecentlyShippedGoods();
  const existingGood = recentlyShippedGoodsPack.find((good) => good.name === query);
  if (existingGood) {
    existingGood.count++;
  } else {
    const newGood = { name: query, count: 1 };
    if (recentlyShippedGoodsPack.length < 10) {
      recentlyShippedGoodsPack.push(newGood);
    } else {
      let minCountIndex = 0;
      for (let i = 1; i < recentlyShippedGoodsPack.length; i++) {
        if (recentlyShippedGoodsPack[i].count < recentlyShippedGoodsPack[minCountIndex].count) {
          minCountIndex = i;
        }
      }
      recentlyShippedGoodsPack.splice(minCountIndex, 1, newGood);
    }
  }
  saveRecentlyShippedGoods(recentlyShippedGoodsPack);
}

// 常用货物类型包装  ssopSign: string | number; // 1货物包装 2货物类型 3货物包装
async function initList() {
  const params = {
    ssopSign: 3,
    ssopRemark: ""
  };
  const res = await getNameGoods(params);
  if (res.data.code == 200) {
    list.value = res.data.data;
    elevatorList.value = transformList(res.data.data)
  }
}


const transformList = (list: any) => {
  let arr: any = []
  let obj = {}
  for (let i = 0; i < list.length; i++) {
    let firstLetter = (pinyin(list[i].ssopRemark, { pattern: 'first', toneType: 'none', type: 'array' })[0]).toUpperCase()
    if (!obj[firstLetter]) {
      obj[firstLetter] = [{ ...list[i], name: list[i].ssopRemark, id: list[i].ssopId }]
    }
    else {
      obj[firstLetter].push({ ...list[i], name: list[i].ssopRemark, id: list[i].ssopId })
    }
  }
  for (let key in obj) {
    arr.push({
      title: key,
      list: obj[key]
    })
  }
  arr.sort((a, b) => {
    return a.title.charCodeAt() - b.title.charCodeAt()
  })
  return arr
}

const goback = () => {
  Taro.navigateBack()
}

</script>
<style lang="scss">
page {
  background-color: #f5f5f5;
  --nut-tabs-horizontal-tab-line-color: #0966ff;
  --nut-tabs-horizontal-titles-item-min-width: 240rpx;
  --nut-elevator-list-item-bars-inner-item-active-color: #0966ff;

  .nut-elevator__list .nut-elevator__list__fixed__wrapper {
    display: none;
  }

  overflow: hidden;
}

.goods-container {
  .nut-tabs__titles {
    padding: 0;
  }

  width: 100%;
  box-sizing: border-box;
  padding: 24rpx;

  .header {
    width: 100%;
    align-items: center;
    display: flex;
    height: 88rpx;
    position: relative;

    .nut-input {
      padding: 20rpx;
      height: 88rpx;
      box-sizing: border-box;
      border-radius: 8rpx 0 0 8rpx;
    }

    .left {
      height: 100%;
    }

    .cancel {
      width: 112rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      background-color: #0966ff;
      font-size: 28rpx;
      border-radius: 0 8rpx 8rpx 0;
    }

    .select-list {
      z-index: 30;
      width: 100%;
      position: absolute;
      top: 104rpx;
      left: 0;
      border-radius: 16rpx;
      overflow: hidden;
      background-color: #fff;

      .select-item {
        width: 100%;
        height: 80rpx;
        box-sizing: border-box;
        padding: 0 24rpx;
        line-height: 80rpx;
        font-size: 24rpx;
        color: #252525;
        border-bottom: 1rpx splid #f5f5f5;

        &:last-child {
          border: none;
        }
      }
    }
  }

  .tabs {
    background-color: #f5f5f5;

    .nut-tabs__titles .nut-tabs__list {
      width: auto;

      &.nut-tabs__titles-item {
        width: auto !important;
      }
    }

    .nut-tab-pane {
      background-color: #f5f5f5;
      padding: 0;
    }

    .historys {
      width: calc(100% + 24rpx);
      display: flex;
      flex-wrap: wrap;

      .history-item {
        padding: 0 24rpx;
        font-size: 24rpx;
        line-height: 56rpx;
        border-radius: 28rpx;
        margin-right: 24rpx;
        margin-top: 24rpx;
        background-color: #fff;
        color: #252525;
      }
    }

    .elevators {
      width: 100%;
      overflow: hidden;
      box-sizing: border-box;
      padding-bottom: 24rpx;
    }
  }
}
</style>
